package com.sntk.organauthomanager.domain.model;

import com.sntk.organauthomanager.infrastructure.exception.DataNoLegalException;
import com.sntk.organauthomanager.infrastructure.exception.ObjectDisbaledException;
import lombok.Getter;
import org.springframework.util.StringUtils;

/**
 * @ClassName: MenuResource
 * @author: wgchao
 * @createTime: 2020/7/17 3:06 PM
 * @Description: 资源
 */
@Getter
public class Resource extends AggregateRoot {

    //资源标识
    private String mark;

    //资源名称
    private String name;

    //资源类型
    private ResourceType resourceType;

    //资源深度 1代表一级
    private int depth;

    private boolean disabled;

    private String parentResource;

    public Resource(Long id, String mark, String name, ResourceType resourceType, int depth,
                    boolean disabled, String parentResource, Long version) {
        if(StringUtils.isEmpty(mark)){
            throw new DataNoLegalException("资源标识不能为空");
        }
        if(StringUtils.isEmpty(name)){
            throw new DataNoLegalException("资源名称不能为空");
        }
        if(resourceType == null){
            throw new DataNoLegalException("资源类型不能为空");
        }
        if(depth <= 0){
            throw new DataNoLegalException("资源深度不能为空");
        }
        setId(id);
        this.mark = mark;
        this.name = name;
        this.resourceType = resourceType;
        this.depth = depth;
        this.disabled = disabled;
        this.parentResource = parentResource;
        setVersion(version);
    }

    public static Resource generate(String mark, String name, ResourceType resourceType,
                                    Resource parentResource){
        if(parentResource != null){
            parentResource.normalException();
        }
        int depth = 1;
        if(parentResource != null){
            depth = parentResource.depth + 1;
        }
        if(parentResource == null && resourceType != ResourceType.PRO){
            throw new DataNoLegalException("顶级资源类型必须为项目");
        }
        return new Resource(-1L, mark, name, resourceType, depth,false,
                parentResource==null ? null : parentResource.getMark(), null);
    }

    public void modifyMenuInfo(String name, boolean disabled){
        if(StringUtils.isEmpty(name)){
            throw new DataNoLegalException("资源名称不能为空");
        }
        this.name = name;
        this.disabled = disabled;
    }

    public boolean normal(){
        return !this.disabled;
    }

    public void normalException(){
        if(!normal()){
            throw new ObjectDisbaledException(this.name+"资源不可用");
        }
    }
}
